package com.foreveross.crawl.adapter.sub.impl20140402.v3.qunar;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import com.foreveross.crawl.adapter.sub.impl20140402.v3.QunarAdapter;
import com.foreveross.crawl.common.QueryJavaScriptEngine;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class QunarDomesticOneWay {
	protected Log logger = LogFactory.getLog(getClass());
	private TaskModel taskQueue;
	private QunarAdapter adapter;
	
	public QunarDomesticOneWay(QunarAdapter adapter,TaskModel taskQueue) {
		this.adapter=adapter;
		this.taskQueue=taskQueue;
	}
	
	public  Object fetch() throws Exception{
		String wyf;
		HtmlPage webPage;
		HtmlPage wyfPage;
		ScriptResult sr;
		String pageofWeb;
		String page;
		String webUrl;
		String url;
		WebClient clent=null;
		HttpClient h = null;
		HttpGet g = null;
		JSONObject j;
		try {
			webUrl=this.getUrlForWebclient();
			clent=adapter.getWebClient();
			clent.getOptions().setCssEnabled(false);
			clent.setJavaScriptEngine(new QueryJavaScriptEngine(clent));
			webPage=clent.getPage(webUrl);
			clent.waitForBackgroundJavaScript(1000*3);
			sr=webPage.executeJavaScript("UA_obj.reloadUA(new Date());document.write(UA_obj.UADATA);");
			wyfPage=(HtmlPage) sr.getNewPage();
			wyf=wyfPage.asText();
			pageofWeb=webPage.asXml();
			adapter.appendPageContents(pageofWeb);//设置源网页数据
			adapter.setLenghtCount(pageofWeb.length());
			clent.closeAllWindows();
			clent=null;
			webPage=null;
			wyfPage=null;
			
			url=this.getUrlForHttpClient(wyf);
			h=adapter.getHttpClient();
			g= new HttpGet(url);
			adapter.setCookiesToMethodByPing("http://flight.qunar.com/", h, g);
			page=adapter.excuteRequest(h,g, true);
			adapter.appendPageContents(page);//设置源网页数据
			j = JSONObject.fromObject(page.trim().replaceAll("^\\(|\\)$", ""));
			return j;
//			boolean isJson=false;
//			try {
//				isJson=adapter.validateFetch(j);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			if(isJson)
//				return adapter.paraseDomeOneWay((Object)j);
//			else
//				return
//					adapter.newParaseDomeOneWay(pageofWeb);
		}finally {
			wyf=null;
			webPage=null;
			wyfPage=null;
			sr=null;
			pageofWeb=null;
			page=null;
			webUrl=null;
			url=null;
			if(null!=clent)
				clent.closeAllWindows();
			clent=null;
			g=null;
			j=null;
		}
		
		
		
	}
	

	/**
	 * 获得用于webclient的url
	 * @return
	 * @throws Exception
	 */
	private String getUrlForWebclient() throws Exception {
		String url="http://flight.qunar.com/site/oneway_list.htm";
		Map<String, String> p = new HashMap<String, String>();
		p.put("searchDepartureAirport", adapter.getCity(taskQueue.getFromCityName()));
		p.put("searchArrivalAirport", adapter.getCity(taskQueue.getToCityName()));
		p.put("searchDepartureTime", taskQueue.getFlightDate());
		p.put("searchArrivalTime", taskQueue.getReturnGrabDate());
		p.put("nextNDays", "0");
		p.put("startSearch", "true");
		p.put("from", "qunarindex");
		return adapter.getBaseGetUrl(url, p);
	}
	
	/**
	 * 获得用于httpclient的Url 
	 * @param wyf
	 * @return
	 * @throws Exception 
	 */
	private String getUrlForHttpClient(String wyf) throws Exception {
		String url="http://flight.qunar.com/twell/longwell";
		Map<String, String> p = new HashMap<String, String>();
		int token=(int) (Math.random()*100000);
		p.put("_token", token+"");
		p.put("from", "qunarindex");
		p.put("http://www.travelco.com/searchDepartureAirport", adapter.getCity(this.taskQueue.getFromCityName()));
		p.put("http://www.travelco.com/searchArrivalAirport", adapter.getCity(this.taskQueue.getToCityName()));
		p.put("http://www.travelco.com/searchDepartureTime", taskQueue.getFlightDate());
		p.put("http://www.travelco.com/searchReturnTime", taskQueue.getFlightDate());
		p.put("locale", "zh");
		p.put("mergeFlag", "0");
		p.put("nextNDays", "0");
		p.put("prePay", "true");
		p.put("searchLangs", "zh");
		p.put("searchType", "OneWayFlight");
		p.put("tags", "1");
		p.put("www", "true");
		p.put("xd", "f" + System.currentTimeMillis());
		p.put("wyf", wyf);
		return adapter.getBaseGetUrl(url, p);
	}

}
